﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Utils.Collections;

namespace Utils.App
{
    public class GOManager<T> : GOAbstractManager where T : GameObject, new() 
    {
        protected Pool<T> pool;
        protected List<T> list;

        public List<T> List { get { return list; } }

        public GOManager(int poolSize)
        {
            this.poolSize = poolSize;
            pool = new Pool<T>(poolSize);
            list = new List<T>(poolSize);
        }

        public virtual T Create()
        {
            T instance = pool.Get();
            list.Add(instance);

            if (GOCreateEvent != null)
            {
                GOCreateEvent(instance, EventArgs.Empty);
            }

            return instance;
        }

        public virtual void Destroy(T instance)
        {
            if (list.Remove(instance))
            {
                if (GODestroyEvent != null)
                {
                    GODestroyEvent(instance, EventArgs.Empty);
                }

                pool.Redeem(instance);
            }
        }

        public virtual void Update(float dTime)
        {
            for (int i = list.Count - 1; i >= 0; i--)
            {
                T go = list[i];
                go.Update(dTime);
                if (go.Dead && go.References <= 0)
                {
                    go.Dead = false;
                    Destroy(go);
                }
            }
        }
    }
}
